package com.bdqn.servlet;

import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysRoleService;
import com.bdqn.service.SysRoleServiceImpl;
import com.bdqn.service.SysUserService;
import com.bdqn.service.SysUserServiceImpl;
import com.bdqn.util.Page;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * SysUserServlet
 *
 * @author LILIBO
 * @since 2021-11-18
 */
@WebServlet("/user")
public class SysUserServlet extends HttpServlet {

    // 服务层接口
    private SysUserService sysUserService = new SysUserServiceImpl();
    private SysRoleService sysRoleService = new SysRoleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        PrintWriter out = response.getWriter();

        String opr = request.getParameter("opr");

        switch (opr) {
            case "toLogin":
                toLogin(request, response, "/WEB-INF/jsp/login.jsp");
                break;
            case "login":
                doLogin(request, response, session);
                break;
            case "logout":
                doLogout(request, response, session);
                break;
            case "list":
                toList(request, response);
                break;
            case "add":
                break;
            case "update":
                break;
            case "del":
                doDel(request, response, out);
                break;
        }

        out.flush();
        out.close();
    }

    /**
     * 删除用户数据
     *
     * @param request
     * @param response
     */
    private void doDel(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        // 获取参数
        String _id = request.getParameter("id");
        if (StringUtils.isEmpty(_id)) {
            out.print("{\"delResult\":\"notexist\"}");
            return;
        }
        Long id = Long.parseLong(_id);

        // 查询用户是否存在
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            out.print("{\"delResult\":\"notexist\"}");
            return;
        }

        // 根据ID删除用户
        int result = sysUserService.delById(id);
        if (result == 1) {
            out.print("{\"delResult\":\"true\"}");
            return;
        } else {
            out.print("{\"delResult\":\"false\"}");
            return;
        }
    }

    /**
     * 显示列表
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void toList(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取参数
        String queryRealName = request.getParameter("queryRealName");
        String _queryRoleId = request.getParameter("queryRoleId");
        String _pageIndex = request.getParameter("pageIndex");
        long queryRoleId = StringUtils.isNotEmpty(_queryRoleId) ? Long.valueOf(_queryRoleId) : 0;
        int pageIndex = StringUtils.isNotEmpty(_pageIndex) ? Integer.valueOf(_pageIndex) : 1; // 默认查第1页

        // 查询所有角色
        List<SysRole> roleList = sysRoleService.getList();

        // 查询第一页用户数据

        // 封装查询参数
        SysUser querySysUser = new SysUser();
        querySysUser.setRealName(queryRealName);
        querySysUser.setRoleId(queryRoleId);

        Page<SysUser> page = new Page<>();
        page.setCurrPageNo(pageIndex); // 设置要查询第几页
        page.setTotalCount(sysUserService.getCount(querySysUser)); // 设置总数据量
        page.setList(sysUserService.getPageList(querySysUser, page)); // 分页查询用户列表

        // 设置到作用域
        request.setAttribute("queryRealName", queryRealName); // 数据回显
        request.setAttribute("queryRoleId", queryRoleId); // 数据回显
        request.setAttribute("roleList", roleList);
        request.setAttribute("page", page);

        // 跳转页面
        request.getRequestDispatcher("/WEB-INF/jsp/sysUser/list.jsp").forward(request, response);
    }

    private void doLogout(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        session.removeAttribute("USER_SESSION");
        session.invalidate(); // 清除Session
        // 重定向（让浏览器重新发起一次请求）
        response.sendRedirect(request.getContextPath() + "/user?opr=toLogin");
    }

    private void doLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException, ServletException {
        // 获取页面参数
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            // 重定向（让浏览器重新发起一次请求）
            response.sendRedirect(request.getContextPath() + "/user?opr=toLogin");
        }
        // 进行业务处理
        SysUser sysUser = sysUserService.login(account, password);
        if (sysUser != null) {
            // 登录成功，将用户对象设置到Session作用域
            session.setAttribute("USER_SESSION", sysUser);
            // 页面转发
            toLogin(request, response, "/WEB-INF/jsp/frame.jsp");
        }
    }

    private void toLogin(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException {
        // 获取页面参数
        // 进行业务处理
        // 页面转发
        request.getRequestDispatcher(url).forward(request, response);
    }
}
